# 订单控制器
from flask import Blueprint, request, jsonify
from service.repair_order import RepairOrderService

# 创建蓝图
order_bp = Blueprint('order', __name__, url_prefix='/orders')

@order_bp.route('/list', methods=['GET'])
def get_orders():
    # 获取单个订单、用户的所有订单或所有订单
    order_id = request.args.get('id')
    user_id = request.args.get('user_id')
    master_id = request.args.get('master_id')

    if order_id:
        return RepairOrderService.get_order_by_id(order_id)
    else:
        return RepairOrderService.get_all_orders(request.args)

@order_bp.route('/add', methods=['POST'])
def create_order():
    # 创建新订单
    data = request.get_json() or {} 
    if not data:
        return jsonify({'code': 10002, 'message': 'No input data provided', 'data': None}), 400
    return RepairOrderService.create_order(data)

@order_bp.route('/edit', methods=['POST'])
def update_order():
    # 更新订单
    data = request.get_json() or {} 
    if not data or 'id' not in data:
        return jsonify({'code': 10002, 'message': 'Order ID is required', 'data': None}), 400
    order_id = data.pop('id')
    return RepairOrderService.update_order(order_id, data)

# 获取用户订单统计
@order_bp.route('/stats', methods=['GET'])
def get_user_order_stats():
    user_id = request.args.get('user_id')
    master_id = request.args.get('master_id')
    return RepairOrderService.get_user_order_stats(user_id, master_id)
